/*
 * @Description: Selector
 * @Author: 0001100986/LiuShuai
 * @Date: 2023-04-26 10:20:56
 * @LastEditTime: 2024-03-20 10:33:48
 * @LastEditors: 0001101185/DingYi
 */
export default {
  name: 'Selector',
  props: {
    // 站点ID
    siteId: {
      type: Number,
      default: 0
    },
    // 网元ID
    neId: {
      type: Number,
      default: 0
    },
    // 选择器类型
    type: {
      type: String,
      default: 'ne'
    },
    // 弹出窗 - 标题
    title: {
      type: String,
      default: '选择器'
    },
    // 弹出窗 - 宽度
    width: {
      type: String,
      default: '50%'
    },
    // 弹出窗 - 遮罩层
    modal: {
      type: Boolean,
      default: true
    },
    appendToBody: {
      type: Boolean,
      default: false
    },
    // 弹出窗 - 点击 modal 关闭 Dialog
    modalEsc: {
      type: Boolean,
      default: true
    },
    // 弹出窗 - 按下 ESC 关闭 Dialog
    modalClick: {
      type: Boolean,
      default: true
    },
    // 搜索 - 是否显示
    search: {
      type: Boolean,
      default: false
    },
    // 搜索 - 条件
    // 示例：
    // condition: [{
    //   key: 'name',
    //   label: '名称',
    //   type: 'text'
    // }, {
    //   key: 'status',
    //   label: '状态',
    //   type: 'select',
    //   default: 'online',
    //   select: [{
    //     label: '在线',
    //     value: 'online'
    //   }, {
    //     label: '离线',
    //     value: 'offline'
    //   }]
    // }]
    condition: {
      type: Array,
      default: []
    },
    // 表格高度
    maxHeight: {
      type: String,
      default: '350px'
    },
    // 支持单选/多选
    selection: {
      type: Boolean,
      default: true
    },
    // 唯一标识
    selKey: {
      type: String,
      default: 'id'
    },
    // 回显字段
    revealKey: {
      type: String,
      default: 'userlabel'
    },
    // 选择器 - 默认值
    defaultVal: {
      type: Array,
      default: []
    },
    // 外部传参
    params: {
      type: Object,
      default: {}
    },
    // input占位符
    placeholder: {
      type: String,
      default: '请输入'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      // 弹出框
      visible: false,
      // 选择器类型 - 匹配
      filter: {
        // 网元选择器
        ne: '/api/sdwan/ne/queryNEWithSite',
        // 站点选择器
        site: '/api/sdwan/site/query',
        // 租户选择器
        tenant: '/api/sdwan/tenant/getMultiDg',
        // VPN选择器
        vpn: '/api/sdwan/vpn/query',
        // DNS选择器
        dns: '/api/sdwan/dns/query',
        // POP选择器
        pop: '/api/sdwan/popgroup/pop/query',
        // 接口选择器
        interface: '/api/resource/nemng/command',
        // CPE站点选择器
        cpeSite: '/api/sdwan/ne/queryNEWithHubSiteId',
        // 命令码
        command: '/api/resource/nemng/command',
        // 告警模板选择器
        template: '/api/fm/template/queryTemplate'
      },
      // 搜索条件
      form: {},
      // 列表数据
      tableData: [],
      // 分页参数
      page: {
        // 当前页
        current: 1,
        // 当前页范围
        size: 15,
        // 总页数
        total: 0
      },
      // 选择结果
      result: [],
      // 加载中...
      loading: false,
      // input - 回显值
      selVal: '',
      // 已选择的总数
      selectedNums: 0,
    };
  },
  created () {
    let _this = this;
    let ary = [];
    let result = [];
    // 存在默认值
    if (_this.defaultVal.length !== 0) {
      for (let i = 0; i < _this.defaultVal.length; i++) {
        if (_this.revealKey.indexOf('.') > -1) {
          let keys = _this.revealKey.split('.');
          ary.push(_this.defaultVal[i][keys[0]][keys[1]]);
        } else {
          ary.push(_this.defaultVal[i][_this.revealKey]);
        }
        result.push(_this.defaultVal[i]);
      }
      // 默认值回显
      _this.selVal = ary.join(',');
      // 写入已选中集合
      _this.result = result;
    }
  },
  mounted () {
    let _this = this;
    _this.$nextTick(() => { });
  },
  watch: {
    // 搜索条件初始值
    search: {
      handler (val) {
        if (val) {
          let _this = this;
          let obj = {};
          if (_this.search) {
            for (let i = 0; i < _this.condition.length; i++) {
              obj[_this.condition[i].key] = _this.condition[i].default || null;
            }
          }
          _this.form = obj;
        }
      },
      deep: true,
      immediate: true
    },
    // 选中值
    tableData: {
      handler (val) {
        if (val) {
          let _this = this;
          _this.$refs['table'].clearSelection();
          for (let i = 0; i < val.length; i++) {
            let ind = _this.result.findIndex(it => {
              return it[_this.selKey] === val[i][_this.selKey];
            });
            if (ind > -1) {
              _this.$refs['table'].toggleRowSelection(val[i], true);
            }
          }
        }
      },
      deep: true,
      immediate: true
    },
    result: {
      handler (val) {
        if (val?.length > 0) {
          this.selectedNums = val.length;
        } else {
          this.selectedNums = 0;
        }
      }
    }
  },
  methods: {
    // 选择器 - 开启
    openSelector () {
      let _this = this;
      _this.visible = true;
      _this.$nextTick(() => {
        _this.$refs['table'].clearSelection();
        _this.initData();
      });
    },
    // 选择器 - 关闭
    handleClose () {
      let _this = this;
      // 清空搜索条件
      _this.form = {};
      _this.visible = false;
    },
    // 选择器 - 确认
    handleConfirm () {
      let _this = this;
      let ary = [];
      for (let i = 0; i < _this.result.length; i++) {
        if (_this.revealKey.indexOf('.') > -1) {
          let keys = _this.revealKey.split('.');
          ary.push(_this.result[i][keys[0]][keys[1]]);
        } else {
          ary.push(_this.result[i][_this.revealKey]);
        }
      }
      _this.selVal = ary.join(',');
      // 推送父组件
      _this.$emit('update:value', _this.result);
      _this.visible = false;
    },
    // 全选 禁用/启用
    allClass ({ row, column, rowIndex, columnIndex }) {
      if (!this.selection && columnIndex === 0) {
        return 'selAllDis';
      }
    },
    // 查询
    handleSearch () {
      let _this = this;
      _this.page.current = 1;
      _this.initData();
    },
    // 初始化
    initData () {
      let _this = this;
      _this.loading = true;
      let params = {
        url: _this.filter[_this.type],
        data: {
          limit: _this.page.size,
          offset: (_this.page.current - 1) * _this.page.size
        }
      };
      if (_this.search) {
        for (let i = 0; i < _this.condition.length; i++) {
          params.data[_this.condition[i].key] = _this.form[_this.condition[i].key];
        }
      }
      // CPE站点选择器
      if (_this.type === 'cpeSite') {
        params.data.siteId = _this.siteId;
      }
      // 使用命令码调用
      if (_this.type === 'command') {
        params.url = params.url + '/' + _this.neId;
        params.data.paras = {
          ...params.data
        };
        params.data.commandCode = _this.params['commandCode'];
        let newParas = Object.assign({}, params.data);
        delete newParas.limit;
        delete newParas.offset;
        params.data = newParas;
      }
      // 接口选择器
      if (_this.type === 'interface') {
        params.url = params.url + '/' + _this.neId;
        params.data.paras = {
          ...params.data
        };
        params.data.paras.use = _this.params['type'];
        params.data.commandCode = 'intfselector.get';
        let newParas = Object.assign({}, params.data);
        delete newParas.limit;
        delete newParas.offset;
        params.data = newParas;
      }
      _this.$http.post(params).then(res => {
        let { status, resultBody, total, dataList, objects, count } = res;
        // 正常返回值
        if (status === '0') {
          let { count, objects } = resultBody;
          _this.page.total = count;
          _this.tableData = objects;
          _this.loading = false;
        }
        // 结果返回值
        if (dataList && dataList.length > 0) {
          if (_this.type === 'template') {
            // 去除第一条模板数据
            dataList.shift();
          }
          _this.page.total = total;
          _this.tableData = dataList;
          _this.loading = false;
        }
        // 命令码或接口选择器返回格式
        if (objects) {
          _this.page.total = count || total;
          _this.tableData = objects;
          _this.loading = false;
        }
      }).catch(() => {
        _this.tableData = [];
        _this.loading = false;
      });
    },
    // 当前页范围
    handleSizeChange (page) {
      let _this = this;
      _this.page.current = 1;
      _this.page.size = page;
      _this.$refs['table'].clearSelection();
      _this.initData();
    },
    // 跳转页码
    currentChange (current) {
      let _this = this;
      _this.page.current = current;
      _this.$refs['table'].clearSelection();
      _this.initData();
    },
    // 唯一标识
    rowKey (row) {
      let _this = this;
      return row[_this.selKey];
    },
    // 全选
    handleSelectAll (sel) {
      let _this = this;
      if (sel.length === 0) {
        _this.$refs['table'].selection = [];
        for (let i = 0; i < _this.tableData.length; i++) {
          let ind = _this.result.findIndex(it => {
            return it[_this.selKey] === _this.tableData[i][_this.selKey];
          });
          if (ind > -1) {
            _this.result.splice(ind, 1);
          }
        }
      } else {
        _this.$refs['table'].selection = _this.tableData;
        for (let i = 0; i < _this.tableData.length; i++) {
          let ind = _this.result.findIndex(it => {
            return it[_this.selKey] === _this.tableData[i][_this.selKey];
          });
          if (ind === -1) {
            _this.result.push(_this.tableData[i]);
          }
        }
      }
    },
    // 勾选项
    handleSelectionChange (sel, row) {
      let _this = this;
      // 单选
      if (!_this.selection) {
        _this.result = [];
        if (sel.length > 0) {
          _this.$refs['table'].clearSelection();
          _this.$refs['table'].toggleRowSelection(row, true);
          _this.$refs['table'].setCurrentRow(row, true);
          _this.$refs['table'].selection = [row];
          _this.result = [row];
        } else {
          _this.$refs['table'].selection = [];
          _this.result = [];
        }
      } else {
        let index = _this.result.findIndex(it => {
          return it[_this.selKey] === row[_this.selKey];
        });
        if (index === -1) {
          _this.result.push(row);
        } else {
          _this.result.splice(index, 1);
        }
      }
    },
    // 行选择
    handleSelectRow (row, column, event) {
      let _this = this;
      let sel = _this.$refs['table'].selection;
      let ind = sel.findIndex(it => {
        return it[_this.selKey] === row[_this.selKey];
      });
      // 单选判断
      if (!_this.selection) {
        _this.result = [];
        _this.$refs['table'].clearSelection();
        if (ind === -1) {
          _this.$refs['table'].toggleRowSelection(row, true);
          _this.$refs['table'].setCurrentRow(row, true);
          _this.$refs['table'].selection = [row];
          _this.result.push(row);
        } else {
          _this.$refs['table'].selection = [];
          _this.result = [];
        }
      } else {
        // 多选
        if (ind === -1) {
          _this.$refs['table'].toggleRowSelection(row, true);
          _this.$refs['table'].setCurrentRow(row, true);
          _this.result.push(row);
        } else {
          _this.$refs['table'].toggleRowSelection(sel[ind], false);
          _this.$refs['table'].setCurrentRow(sel[ind], false);
          let index = _this.result.findIndex(it => {
            return it[_this.selKey] === row[_this.selKey];
          });
          _this.result.splice(index, 1);
        }
      }
    },
    // 清除数据
    clearValue () {
      let _this = this;
      // 阻止事件穿透
      event.stopPropagation();
      _this.result = [];
      _this.selVal = null;
      // 推送父组件
      _this.$emit('update:value', _this.result);
    }
  }
};